package com.rayo.accesscontrollercopy.model.biz;

import android.content.Context;
import android.content.Intent;
import android.util.SparseArray;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rayo.accesscontrollercopy.config.GlobalVariables;
import com.rayo.accesscontrollercopy.config.OfficeModeConfig;
import com.rayo.accesscontrollercopy.model.callback.ApiCallback;
import com.rayo.accesscontrollercopy.model.callback.OnGetDbListener;
import com.rayo.accesscontrollercopy.model.callback.OnNetworkListener;
import com.rayo.accesscontrollercopy.model.callback.OnUpdateDbListener;
import com.rayo.accesscontrollercopy.model.db.bean.BlackListData;
import com.rayo.accesscontrollercopy.model.db.bean.CalendarData;
import com.rayo.accesscontrollercopy.model.db.bean.CardTimezoneData;
import com.rayo.accesscontrollercopy.model.db.bean.CardUserData;
import com.rayo.accesscontrollercopy.model.db.bean.DSTData;
import com.rayo.accesscontrollercopy.model.db.bean.EventData;
import com.rayo.accesscontrollercopy.model.db.bean.HeartData;
import com.rayo.accesscontrollercopy.model.db.bean.KeyTimezoneData;
import com.rayo.accesscontrollercopy.model.db.bean.KeyUserData;
import com.rayo.accesscontrollercopy.model.db.bean.LockData;
import com.rayo.accesscontrollercopy.model.db.bean.OperatorData;
import com.rayo.accesscontrollercopy.model.db.bean.PlanKeyAddData;
import com.rayo.accesscontrollercopy.model.db.bean.PlanKeyTempData;
import com.rayo.accesscontrollercopy.model.db.bean.SiteData;
import com.rayo.accesscontrollercopy.model.db.bean.SystemData;
import com.rayo.accesscontrollercopy.model.db.dao.BlackListDao;
import com.rayo.accesscontrollercopy.model.db.dao.BlackListImpl;
import com.rayo.accesscontrollercopy.model.db.dao.CalendarDao;
import com.rayo.accesscontrollercopy.model.db.dao.CalendarImpl;
import com.rayo.accesscontrollercopy.model.db.dao.CardTimeDao;
import com.rayo.accesscontrollercopy.model.db.dao.CardTimeImpl;
import com.rayo.accesscontrollercopy.model.db.dao.CardUserDao;
import com.rayo.accesscontrollercopy.model.db.dao.CardUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.DSTDao;
import com.rayo.accesscontrollercopy.model.db.dao.DSTImpl;
import com.rayo.accesscontrollercopy.model.db.dao.DmuTimeDao;
import com.rayo.accesscontrollercopy.model.db.dao.DmuTimeImpl;
import com.rayo.accesscontrollercopy.model.db.dao.EventDao;
import com.rayo.accesscontrollercopy.model.db.dao.EventImpl;
import com.rayo.accesscontrollercopy.model.db.dao.HeartDao;
import com.rayo.accesscontrollercopy.model.db.dao.HeartImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyTimeDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyTimeImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyUserDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.LockDao;
import com.rayo.accesscontrollercopy.model.db.dao.LockImp;
import com.rayo.accesscontrollercopy.model.db.dao.OperatorDao;
import com.rayo.accesscontrollercopy.model.db.dao.OperatorImpl;
import com.rayo.accesscontrollercopy.model.db.dao.PlanKeyAddDao;
import com.rayo.accesscontrollercopy.model.db.dao.PlanKeyAddImpl;
import com.rayo.accesscontrollercopy.model.db.dao.PlanKeyTempDao;
import com.rayo.accesscontrollercopy.model.db.dao.PlanKeyTempImpl;
import com.rayo.accesscontrollercopy.model.db.dao.SiteDao;
import com.rayo.accesscontrollercopy.model.db.dao.SiteImpl;
import com.rayo.accesscontrollercopy.model.db.dao.SystemDataDao;
import com.rayo.accesscontrollercopy.model.db.dao.SystemDataImpl;
import com.rayo.accesscontrollercopy.model.network.ApiCmd;
import com.rayo.accesscontrollercopy.model.network.WebSocketHelp;
import com.rayo.accesscontrollercopy.model.network.bean.BaseApi;
import com.rayo.accesscontrollercopy.model.network.bean.LockIdApi;
import com.rayo.accesscontrollercopy.model.network.bean.OpenApi;
import com.rayo.accesscontrollercopy.model.network.bean.UpdateCalenderApi;
import com.rayo.accesscontrollercopy.model.network.bean.UpdateCardTimezonApi;
import com.rayo.accesscontrollercopy.model.network.bean.UpdateEventApi;
import com.rayo.accesscontrollercopy.model.network.bean.UpdateKeyTimezoneApi;
import com.rayo.accesscontrollercopy.model.network.bean.UpdateLockApi;
import com.rayo.accesscontrollercopy.model.network.bean.UpdateLocksApi;
import com.rayo.accesscontrollercopy.model.network.bean.UpdateOperatorApi;
import com.rayo.accesscontrollercopy.model.network.bean.UpdateTimeApi;
import com.rayo.accesscontrollercopy.model.network.bean.UpdateUserApi;
import com.rayo.accesscontrollercopy.model.service.NetworkData;
import com.rayo.wallreader.gpio.OnRelayListener;
import com.rayo.wallreader.gpio.RelayBiz;
import com.rayo.wallreader.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yanghaojie on 16/7/25.
 */
public class NetworkBiz implements INetworkBiz {
    private SystemDataDao systemDataDao = new SystemDataImpl();
    private OnUpdateDbListener mOnUpdateDbListener = null;
    private OnNetworkListener mOnNetworkListener = null;
    private OnGetDbListener mOnGetDbListener = null;
    private ApiCallback mApiCallback = null;

    private HeartDao mHeartDao = new HeartImpl();
    private HeartData mHeartData = new HeartData();
    private String mUrl;

    private SparseArray<Date> mUpdateKeyMap;
    private SparseArray<Date> mUpdateCardMap;
    private Context mContext;
    public NetworkBiz(Context context){
        this.mContext = context;
    }
    @Override
    public void init(OnGetDbListener onGetDbListener, OnNetworkListener onNetworkListener,
                     OnUpdateDbListener onUpdateDbListener, ApiCallback apiCallback) {
        this.mOnGetDbListener = onGetDbListener;
        this.mOnUpdateDbListener = onUpdateDbListener;
        this.mOnNetworkListener = onNetworkListener;
        this.mApiCallback = apiCallback;
        if (null != GlobalVariables.getInstance().getmSystemData()) {
            mOnGetDbListener.onSuccess(GlobalVariables.getInstance().getmSystemData());
        } else {
            SystemData systemData = systemDataDao.findFirst();
            if (null == systemData) {
                systemData = new SystemData();
                systemDataDao.addSystem(systemData);
            }
            GlobalVariables.getInstance().setmSystemData(systemData);
            mOnGetDbListener.onSuccess(systemData);
        }
        mUrl = GlobalVariables.getInstance().getmSystemData().getServerIp()
                + ":" + GlobalVariables.getInstance().getmSystemData().getServerPort();
        WebSocketHelp.getmInstance().init(mApiCallback, mOnNetworkListener);

    }

    @Override
    public void connect() {
        if (null != mUrl && !mUrl.isEmpty()) {
            WebSocketHelp.getmInstance().setmUrl(mUrl);
            WebSocketHelp.getmInstance().connect();
        }
    }

    @Override
    public void updateDb(String lockId) {
        WebSocketHelp.getmInstance().updateDb(lockId,false);
//        SiteData siteData = GlobalVariables.getInstance().getmSiteData();
//        if (!WebSocketHelp.getmInstance().isConnect()) return;
//        if (lockId == null || lockId.isEmpty() || lockId.equals("0")) {
//            if (null != mOnUpdateDbListener)
//                mOnUpdateDbListener.onFailed(NetWorkService.ACTION_NETWORK_UPDATE_DB, "");
//            return;
//        }
//        if (!WebSocketHelp.getmInstance().isConnect()) {
//            if (null != mOnUpdateDbListener)
//                mOnUpdateDbListener.onFailed(NetWorkService.ACTION_NETWORK_UPDATE_DB, "");
//            return;
//        }
//        mHeartData = mHeartDao.findById(GlobalVariables.getInstance().getmSiteData().getSite(),
//                Integer.valueOf(lockId));
//        HeartApi heartApi = new HeartApi();
//        heartApi.setLockid(lockId);
//        if (null == mHeartData) {
//            heartApi.setKeyuser(TimeUtils.dateFromNotYMDHM("0101020101"));
//            heartApi.setCarduser(TimeUtils.dateFromNotYMDHM("0101020101"));
//        } else {
//            heartApi.setKeyuser(mHeartData.getKeyusertime());
//            heartApi.setCarduser(mHeartData.getCardusertime());
//        }
//        WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(new BaseApi(ApiCmd.HEART,
//                GlobalVariables.getInstance().getmSiteData().getSite(), heartApi)));
//        WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(new BaseApi(ApiCmd.HEART,
//                GlobalVariables.getInstance().getmSiteData().getSite(), heartApi)), new ApiCallback() {
//            @Override
//            public <T> void onSuccess(byte cmd, T ret) {
//                switch (cmd) {
//                    case ApiCmd.HEART:
//                        break;
//                    case ApiCmd.UPDATE_ID:
//                        break;
//                    case ApiCmd.UPDATE_OPERATOR:
//                        break;
//                    case ApiCmd.UPDATE_KEY:
//                        break;
//                    case ApiCmd.UPDATE_CARD:
//                        if (null != mOnUpdateDbListener)
//                            mOnUpdateDbListener.onSuccess(NetWorkService.ACTION_NETWORK_UPDATE_DB, null);
//                        break;
//                    default:
//                        break;
//                }
//            }
//
//            @Override
//            public void onError(String err_msg) {
//                if (null != mOnUpdateDbListener)
//                    mOnUpdateDbListener.onFailed(NetWorkService.ACTION_NETWORK_UPDATE_DB, err_msg);
//            }
//
//            @Override
//            public void onFailure() {
//                if (null != mOnUpdateDbListener)
//                    mOnUpdateDbListener.onFailed(NetWorkService.ACTION_NETWORK_UPDATE_DB, "");
//            }
//        });
    }

    @Override
    public void updateOperator(HeartData heartData) {
        if (heartData.getOperator().getTime() > mHeartData.getOperator().getTime()) {
            BaseApi baseApi = new BaseApi(ApiCmd.UPDATE_OPERATOR, GlobalVariables.getInstance().getmSiteData().getSite(),
                    new UpdateTimeApi(mHeartData.getOperator()));
            WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi));
        }
    }

    @Override
    public void updateKeyTimezone(HeartData heartData) {
        if (heartData.getTimezone().getTime() > mHeartData.getTimezone().getTime()) {
            BaseApi baseApi = new BaseApi(ApiCmd.UPDATE_USER_TIMEZONE, GlobalVariables.getInstance().getmSiteData().getSite(),
                    new UpdateTimeApi(mHeartData.getTimezone()));
            WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi));
        }
    }

    @Override
    public void updateCardTimezone(HeartData heartData) {
        if (heartData.getCardtime().getTime() > mHeartData.getCardtime().getTime()) {
            BaseApi baseApi = new BaseApi(ApiCmd.UPDATE_CARD_TIMEZONE, GlobalVariables.getInstance().getmSiteData().getSite(),
                    new UpdateTimeApi(mHeartData.getCardtime()));
            WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi));
        }
    }

    @Override
    public void updateCalendar(HeartData heartData) {
        if (heartData.getCalendar().getTime() > mHeartData.getCalendar().getTime()) {
            BaseApi baseApi = new BaseApi(ApiCmd.UPDATE_CALENDER, GlobalVariables.getInstance().getmSiteData().getSite(),
                    new UpdateTimeApi(mHeartData.getCalendar()));
            WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi));
        }
    }

    @Override
    public void updateDST(HeartData heartData) {
        if (heartData.getDst().getTime() > mHeartData.getDst().getTime()) {
            BaseApi baseApi = new BaseApi(ApiCmd.UPDATE_DST, GlobalVariables.getInstance().getmSiteData().getSite(),
                    new UpdateTimeApi(mHeartData.getDst()));
            WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi));
        }
    }

    @Override
    public void updateBlackList(HeartData heartData) {
        if (heartData.getBlacklist().getTime() > mHeartData.getBlacklist().getTime()) {
            BaseApi baseApi = new BaseApi(ApiCmd.UPDATE_BLACKLIST, GlobalVariables.getInstance().getmSiteData().getSite(),
                    new UpdateTimeApi(mHeartData.getBlacklist()));
            WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi));
        }
    }

    @Override
    public void updateLock(String lockId, int status) {
        if (status == 0 || status == 1) {
            BaseApi baseApi = new BaseApi(ApiCmd.UPDATE_ID, GlobalVariables.getInstance().getmSiteData().getSite(),
                    new LockIdApi(lockId));
            WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi));
        }
    }

    @Override
    public void updateKeyUser(List<String> keyList) {
        if (null != keyList && keyList.size() > 0) {
            mUpdateKeyMap = new SparseArray<>();
            KeyUserDao keyUserDao = new KeyUserImpl();
            for (String keyId : keyList) {
                KeyUserData keyUserData = keyUserDao.findByUserid(keyId);
                UpdateUserApi updateUserApi = new UpdateUserApi(keyId, new Date());
                if (keyUserData.getUserid().isEmpty() || keyUserData.getUserid().equals("0")) {
                    updateUserApi.setTime(TimeUtils.dateFromNotYMDHMS("010102010100"));
                } else {
                    updateUserApi.setTime(keyUserData.getEditime());
                }
                mUpdateKeyMap.append(Integer.valueOf(keyId), updateUserApi.getTime());
                WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(new BaseApi(ApiCmd.UPDATE_KEY, GlobalVariables.getInstance().getmSiteData().getSite(), updateUserApi)));
            }
        }
    }

    @Override
    public void updateCardUser(List<String> cardList) {
        if (null != cardList && cardList.size() > 0) {
            mUpdateCardMap = new SparseArray<>();
            CardUserDao cardUserDao = new CardUserImpl();
            for (String keyId : cardList) {
                CardUserData cardUserData = cardUserDao.findByUserId(Integer.valueOf(keyId));
                UpdateUserApi updateUserApi = new UpdateUserApi(keyId, new Date());
                if (cardUserData.getUserid() == 0) {
                    updateUserApi.setTime(TimeUtils.dateFromNotYMDHMS("010102010100"));
                } else {
                    updateUserApi.setTime(cardUserData.getEditime());
                }
                mUpdateCardMap.append(Integer.valueOf(keyId), updateUserApi.getTime());
                WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(new BaseApi(ApiCmd.UPDATE_CARD, GlobalVariables.getInstance().getmSiteData().getSite(), updateUserApi)));
            }
        }
    }

    @Override
    public void updateLocks(List<String> lockList) {
        if (lockList != null && lockList.size() > 0) {
            for (String lockId : lockList) {
                UpdateLocksApi locksApi = new UpdateLocksApi();
                locksApi.setLockid(lockId);
                WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(
                        new BaseApi(ApiCmd.UPDATE_LOCKS, GlobalVariables.getInstance().getmSiteData().getSite(), locksApi)));
            }
        }
    }

    @Override
    public void postEvents() {
        final EventDao eventDao = new EventImpl();
        List<EventData> dataList = eventDao.findAll();
        if (null != dataList && dataList.size() > 0) {
            BaseApi baseApi = new BaseApi(ApiCmd.UPDATE_EVENT, GlobalVariables.getInstance().getmSiteData().getSite(),
                    new UpdateEventApi(dataList));
            WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi));
        }
    }

    @Override
    public void updateApp(Context context) {
        BaseApi baseApi = new BaseApi(ApiCmd.UPDATE_APP,
                GlobalVariables.getInstance().getmSiteData().getSite(), new Object());
        WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi));
//        WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(baseApi), new ApiCallback() {
//            @Override
//            public <T> void onSuccess(byte cmd, T ret) {
//                mOnNetworkListener.onSuccess(NetWorkService.ACTION_NETWORK_UPDATE_APP, ret);
//            }
//
//            @Override
//            public void onError(String err_msg) {
//                mOnNetworkListener.onFailed(NetWorkService.ACTION_NETWORK_UPDATE_APP, err_msg);
//            }
//
//            @Override
//            public void onFailure() {
//                mOnNetworkListener.onFailed(NetWorkService.ACTION_NETWORK_UPDATE_APP, "failed");
//            }
//        });
    }

    @Override
    public NetworkData saveData(byte cmd, JSONObject json) {
        NetworkData networkData = new NetworkData(cmd);
        switch (cmd) {
            case ApiCmd.ERROR:
                Intent intentERROR = new Intent();
                intentERROR.setAction("ERROR");
//                intent.putExtra("ERROR",)
                mContext.sendBroadcast(intentERROR);
                break;
            case ApiCmd.CONNECT:
//                updateDb(String.valueOf(GlobalVariables.getInstance().getmSiteData().getLockid()));
                break;
            case ApiCmd.OPEN:
                OpenApi openApi = JSON.parseObject(json.toJSONString(), OpenApi.class);
                if (GlobalVariables.getInstance().getmSiteData().getLockid() == Integer.valueOf(openApi.getLockid())) {
                    sendBack(ApiCmd.OPEN, "");
                    RelayBiz relayBiz = new RelayBiz(RelayBiz.RELAY1);

                    relayBiz.openRelaySec(GlobalVariables.getInstance().getmSystemData().getDelay(), new OnRelayListener.OnOpenListener() {
                        @Override
                        public void openSuccess() {
                        }

                        @Override
                        public void openFailed() {
                        }

                        @Override
                        public void closeSuccess() {
                        }

                        @Override
                        public void closeFailed() {
                        }
                    });
                } else {
                    sendBack(ApiCmd.ERROR, "lock id is wrong");
                }
                networkData.setData(openApi);
                break;
            case ApiCmd.HEART:
                HeartData heartData = JSON.parseObject(json.toJSONString(), HeartData.class);
                mHeartData = mHeartDao.findById(GlobalVariables.getInstance().getmSiteData().getSite(),
                        Integer.valueOf(heartData.getLockid()));
                if (null == mHeartData) {
                    mHeartData = new HeartData();
                    mHeartData.setSite(GlobalVariables.getInstance().getmSiteData().getSite());
                    mHeartData.setLockid(heartData.getLockid());
                    mHeartData.updateDate(TimeUtils.dateFromNotYMDHMS("010102010100"));
                }
                WebSocketHelp.getmInstance().setAppVersion(heartData.getAppversion());
                updateLock(heartData.getLockid(), heartData.getStatus());
                updateOperator(heartData);
                updateKeyTimezone(heartData);
                updateCalendar(heartData);
                updateCardTimezone(heartData);
                updateBlackList(heartData);
                updateDST(heartData);
                updateKeyUser(heartData.getKeylist());
                updateCardUser(heartData.getCardlist());
                updateLocks(heartData.getLocklist());
                if ((null == mUpdateCardMap || mUpdateCardMap.size() == 0)
                        && (null == mUpdateKeyMap || mUpdateKeyMap.size() == 0)) {
                    mOnGetDbListener.onSuccess(ApiCmd.UPDATE_CARD);
                }
                break;
            case ApiCmd.UPDATE_LOCK:
                LockIdApi lockIdApi = JSON.parseObject(json.toJSONString(), LockIdApi.class);
                if (GlobalVariables.getInstance().getmSiteData().getLockid() == 0
                        || GlobalVariables.getInstance().getmSiteData().getLockid() == Integer.valueOf(lockIdApi.getLockid())) {
                    WebSocketHelp.getmInstance().updateDb(lockIdApi.getLockid(),true);
                } else {
                    WebSocketHelp.getmInstance().sendMessage((byte)ApiCmd.ERROR,JSON.toJSONString(new BaseApi((byte)ApiCmd.ERROR,
                            GlobalVariables.getInstance().getmSiteData().getSite(), "error id")));
                }
                break;
            case ApiCmd.UPDATE_ID:
                UpdateLockApi updateLockApi = JSON.parseObject(json.toJSONString(), UpdateLockApi.class);
                SiteDao siteDao = new SiteImpl();
                SiteData siteData = siteDao.findFirst();
                if (null == siteData) siteData = new SiteData();
                siteData.setSite(updateLockApi.getSite());
                siteData.setLockid(Integer.valueOf(updateLockApi.getLockid()));
                siteData.setGroupid(Integer.valueOf(updateLockApi.getGroupid()));
                siteData.setName(updateLockApi.getName());
                siteData.setMode(updateLockApi.getMode());
                siteData.setRegcode(updateLockApi.getRegcode());
                siteData.setSyscode(updateLockApi.getSyscode());
                siteData.setSupportkey(updateLockApi.getSupportkey());
                if (siteData.getId() == 0)
                    siteDao.addSite(siteData);
                else
                    siteDao.updateSite(siteData);
                mHeartData.setSite(updateLockApi.getSite());
                mHeartData.setLockid(updateLockApi.getLockid());
                mHeartDao.addEvent(mHeartData);
                GlobalVariables.getInstance().setmSiteData(siteData);
                DmuTimeDao dmuTimeDao = new DmuTimeImpl();
                dmuTimeDao.deleteAll();
                dmuTimeDao.addAll(updateLockApi.getTimezone());
                OfficeModeConfig.getInstance().init();
                WebSocketHelp.getmInstance().sendMessage(ApiCmd.UPDATE_LOCK,JSON.toJSONString(new BaseApi(ApiCmd.UPDATE_LOCK,
                        GlobalVariables.getInstance().getmSiteData().getSite(),
                        new LockIdApi(String.valueOf(GlobalVariables.getInstance().getmSiteData().getLockid())))));
                break;
            case ApiCmd.UPDATE_OPERATOR:
                UpdateOperatorApi updateOperatorApi = JSON.parseObject(json.toJSONString(), UpdateOperatorApi.class);
                if (null != updateOperatorApi && updateOperatorApi.getList().size() > 0) {
                    OperatorDao operatorDao = new OperatorImpl();
                    for (OperatorData operatorData : updateOperatorApi.getList()) {
                        OperatorData operatorData1 = operatorDao.findByOperid(operatorData.getOperid());
                        if (null == operatorData1) operatorData1 = new OperatorData();
                        operatorData1.setFirst(operatorData.getFirst());
                        operatorData1.setLast(operatorData.getLast());
                        operatorData1.setOperid(operatorData.getOperid());
                        operatorData1.setLogin(operatorData.getLogin());
                        operatorData1.setPassword(operatorData.getPassword());
                        operatorData1.setAuthority(operatorData.getAuthority());
                        if (operatorData1.getId() == 0) operatorDao.addOperator(operatorData1);
                        else operatorDao.updateOperator(operatorData1);
                    }
                    mHeartData.setOperator(new Date());
                    mHeartDao.addEvent(mHeartData);
                }
                break;
            case ApiCmd.UPDATE_BLACKLIST:
                BlackListData blackListData = JSON.parseObject(json.toJSONString(), BlackListData.class);
                if (null != blackListData) {
                    BlackListDao blackListDao = new BlackListImpl();
                    blackListDao.updateBlackList(blackListData);
                    mHeartData.setBlacklist(new Date());
                    mHeartDao.addEvent(mHeartData);
                }
                break;
            case ApiCmd.UPDATE_USER_TIMEZONE:
                UpdateKeyTimezoneApi updateKeyTimezoneApi = JSON.parseObject(json.toJSONString(), UpdateKeyTimezoneApi.class);
                if (null != updateKeyTimezoneApi && updateKeyTimezoneApi.getList().size() > 0) {
                    KeyTimeDao keyTimeDao = new KeyTimeImpl();
                    for (KeyTimezoneData keyTimezoneData : updateKeyTimezoneApi.getList()) {
                        KeyTimezoneData keyTimezoneData1 = keyTimeDao.findByNo(keyTimezoneData.getNo(), keyTimezoneData.getSerial());
                        if (keyTimezoneData1 == null) {
                            keyTimezoneData1 = new KeyTimezoneData();
                            keyTimezoneData1.setNo(keyTimezoneData.getNo());
                            keyTimezoneData1.setSerial(keyTimezoneData.getSerial());
                            keyTimezoneData1.setFrom(keyTimezoneData.getFrom());
                            keyTimezoneData1.setTo(keyTimezoneData.getTo());
                            keyTimezoneData1.setMon(keyTimezoneData.getMon());
                            keyTimezoneData1.setTue(keyTimezoneData.getTue());
                            keyTimezoneData1.setWed(keyTimezoneData.getWed());
                            keyTimezoneData1.setThu(keyTimezoneData.getThu());
                            keyTimezoneData1.setFri(keyTimezoneData.getFri());
                            keyTimezoneData1.setSat(keyTimezoneData.getSat());
                            keyTimezoneData1.setSun(keyTimezoneData.getSun());
                            keyTimezoneData1.setSp1(keyTimezoneData.getSp1());
                            keyTimezoneData1.setSp2(keyTimezoneData.getSp2());
                            keyTimezoneData1.setHol(keyTimezoneData.getHol());
                            keyTimeDao.addKeyTime(keyTimezoneData1);
                        }
                        else {
                            keyTimezoneData1.setNo(keyTimezoneData.getNo());
                            keyTimezoneData1.setSerial(keyTimezoneData.getSerial());
                            keyTimezoneData1.setFrom(keyTimezoneData.getFrom());
                            keyTimezoneData1.setTo(keyTimezoneData.getTo());
                            keyTimezoneData1.setMon(keyTimezoneData.getMon());
                            keyTimezoneData1.setTue(keyTimezoneData.getTue());
                            keyTimezoneData1.setWed(keyTimezoneData.getWed());
                            keyTimezoneData1.setThu(keyTimezoneData.getThu());
                            keyTimezoneData1.setFri(keyTimezoneData.getFri());
                            keyTimezoneData1.setSat(keyTimezoneData.getSat());
                            keyTimezoneData1.setSun(keyTimezoneData.getSun());
                            keyTimezoneData1.setSp1(keyTimezoneData.getSp1());
                            keyTimezoneData1.setSp2(keyTimezoneData.getSp2());
                            keyTimezoneData1.setHol(keyTimezoneData.getHol());
                            keyTimeDao.updateKeyTime(keyTimezoneData1);
                        }
                    }
                    mHeartData.setTimezone(new Date());
                    mHeartDao.addEvent(mHeartData);
                }
                break;
            case ApiCmd.UPDATE_CARD_TIMEZONE:
                UpdateCardTimezonApi updateCardTimezonApi = JSON.parseObject(json.toJSONString(), UpdateCardTimezonApi.class);
                if (null != updateCardTimezonApi && updateCardTimezonApi.getList().size() > 0) {
                    CardTimeDao cardTimeDao = new CardTimeImpl();
                    for (CardTimezoneData cardTimezoneData : updateCardTimezonApi.getList()) {
                        CardTimezoneData cardTimezoneData1 = cardTimeDao.findByNo(cardTimezoneData.getUserid(), cardTimezoneData.getSerial());
                        if (null == cardTimezoneData1) cardTimezoneData1 = new CardTimezoneData();
                        cardTimezoneData1.setUserid(cardTimezoneData.getUserid());
                        cardTimezoneData1.setSerial(cardTimezoneData.getSerial());
                        cardTimezoneData1.setFrom(cardTimezoneData.getFrom());
                        cardTimezoneData1.setTo(cardTimezoneData.getTo());
                        cardTimezoneData1.setMon(cardTimezoneData.getMon());
                        cardTimezoneData1.setTue(cardTimezoneData.getTue());
                        cardTimezoneData1.setWed(cardTimezoneData.getWed());
                        cardTimezoneData1.setThu(cardTimezoneData.getThu());
                        cardTimezoneData1.setFri(cardTimezoneData.getFri());
                        cardTimezoneData1.setSat(cardTimezoneData.getSat());
                        cardTimezoneData1.setSun(cardTimezoneData.getSun());
                    }
                    mHeartData.setCardtime(new Date());
                    mHeartDao.addEvent(mHeartData);
                }
                break;
            case ApiCmd.UPDATE_CALENDER:
                UpdateCalenderApi updateCalenderApi = JSON.parseObject(json.toJSONString(), UpdateCalenderApi.class);
                if (null != updateCalenderApi && updateCalenderApi.getList().size() > 0) {
                    CalendarDao calendarDao = new CalendarImpl();
                    for (UpdateCalenderApi.CalenderData calenderData : updateCalenderApi.getList()) {
                        int calid = Integer.valueOf(calenderData.getCalid());
                        for (CalendarData calendarData : calenderData.getDatelist()) {
                            calendarData.setCalid(calid);
                        }
                        calendarDao.deleteByCalId(calid);
                        calendarDao.addAll(calenderData.getDatelist());
                    }
                    mHeartData.setCalendar(new Date());
                    mHeartDao.addEvent(mHeartData);
                }
                break;
            case ApiCmd.UPDATE_DST:
                DSTData dstData = JSON.parseObject(json.toJSONString(), DSTData.class);
                if (null != dstData) {
                    DSTDao dstDao = new DSTImpl();
                    dstDao.update(dstData);
                    mHeartData.setDst(new Date());
                    mHeartDao.addEvent(mHeartData);
                }
                break;
            case ApiCmd.UPDATE_KEY:
                KeyUserData keyUserData = JSON.parseObject(json.toJSONString(), KeyUserData.class);
                if (null != keyUserData) {
                    KeyUserDao keyUserDao = new KeyUserImpl();
//                    PlanKeyDelDao planKeyDelDao = new PlanKeyDelImpl();
                    PlanKeyAddDao planKeyAddDao = new PlanKeyAddImpl();
//                    PlanKeyTempDao planKeyTempDao = new PlanKeyTempImpl();
                    if (keyUserData.getFlag() == 0) {
                        keyUserDao.addKeyUser(keyUserData);
                        if (keyUserData.getPlan().length() > 2) {
                            List<PlanKeyAddData> keyAddDataList = new ArrayList<>();
                            String keyAddData = keyUserData.getPlan();
                            while (128 < keyAddData.length()) {
                                keyAddDataList.add(new PlanKeyAddData(Integer.valueOf(keyUserData.getUserid()),
                                        keyAddData.substring(0, 128)));
                                keyAddData = keyAddData.substring(128, keyAddData.length());

                            }
                            keyAddDataList.add(new PlanKeyAddData(Integer.valueOf(keyUserData.getUserid()),
                                    keyAddData));

                            planKeyAddDao.addOrupdateKeyPlan(Integer.valueOf(keyUserData.getUserid()), keyAddDataList);
                        }

//                        if (keyUserData.getDeleteplan().length() > 2) {
//                            List<PlanKeyDelData> keyDelDataList = new ArrayList<>();
//                            String keyDelData = keyUserData.getDeleteplan();
//
//                            while (128 < keyDelData.length()) {
//                                keyDelDataList.add(new PlanKeyDelData(Integer.valueOf(keyUserData.getUserid()),
//                                        keyDelData.substring(0, 128)));
//                                keyDelData = keyDelData.substring(128, keyDelData.length());
//                            }
//                            keyDelDataList.add(new PlanKeyDelData(Integer.valueOf(keyUserData.getUserid()),
//                                    keyDelData));
//                            planKeyDelDao.addOrupdateKeyPlan(Integer.valueOf(keyUserData.getUserid()), keyDelDataList);
//                        }
//                        if (keyUserData.getTemplan().size() > 0) {
//                            for (PlanKeyTempData planKeyTempData : keyUserData.getTemplan()) {
//                                planKeyTempData.setUserid(Integer.valueOf(keyUserData.getUserid()));
//                                planKeyTempDao.addOrUpdateKeyPlan(planKeyTempData);
//                            }
//                        }
                    } else {
                        keyUserDao.deleteByKeyUserId(Integer.valueOf(keyUserData.getUserid()));
                        planKeyAddDao.deleteByUserId(Integer.valueOf(keyUserData.getUserid()));
//                        planKeyDelDao.deleteByUserId(Integer.valueOf(keyUserData.getUserid()));
//                        planKeyTempDao.deletTempKeyPlanById(Integer.valueOf(keyUserData.getUserid()));
                    }
                    mUpdateKeyMap.remove(Integer.valueOf(keyUserData.getUserid()));
                }
                if (null == mUpdateKeyMap || mUpdateKeyMap.size() == 0) {
                    mHeartData.setKeyusertime(new Date());
                    mHeartDao.addEvent(mHeartData);
                    mOnGetDbListener.onSuccess(ApiCmd.UPDATE_KEY);
                }
//                if (keyPos >= keyCount) {
//                    if (keyCount > 0) {
//                        mHeartData.setKeyusertime(new Date());
//                        mHeartDao.addEvent(mHeartData);
//                    }
//                    keyPos = 0;
//                    keyCount = 0;
////                    if (null != mApiCallback)
////                        mApiCallback.onSuccess(ApiCmd.UPDATE_KEY, keyUserData);
//                }
                break;
            case ApiCmd.UPDATE_CARD:
                CardUserData cardUserData = JSON.parseObject(json.toJSONString(), CardUserData.class);

                if (null != cardUserData) {
                    CardUserDao cardUserDao = new CardUserImpl();
                    cardUserDao.addCardUser(cardUserData);
                    mUpdateCardMap.remove(Integer.valueOf(cardUserData.getUserid()));
                }
                if (null == mUpdateCardMap || mUpdateCardMap.size() == 0) {
                    mHeartData.setCardusertime(new Date());
                    mHeartDao.addEvent(mHeartData);
                    mOnGetDbListener.onSuccess(ApiCmd.UPDATE_CARD);
                }
//                if (cardPos >= cardCount) {
//                    if (cardCount > 0) {
//                        mHeartData.setCardusertime(new Date());
//                        mHeartDao.addEvent(mHeartData);
//                    }
//                    cardPos = 0;
//                    cardCount = 0;
////                    if (null != mApiCallback)
////                        mApiCallback.onSuccess(ApiCmd.UPDATE_CARD, cardUserData);
//                }
                break;
            case ApiCmd.UPDATE_EVENT:
                EventDao eventDao = new EventImpl();
                eventDao.deleteAll();
                break;
            case ApiCmd.UPDATE_LOCKS:
                LockDao lockDao = new LockImp();
                LockData lockData = JSON.parseObject(json.toJSONString(), LockData.class);
                if (lockData != null) {
                    if (lockDao.findBylockId(lockData.getLockid()) != null) {
                        lockDao.updateLock(lockData);
                    } else {
                        lockDao.addLock(lockData);
                    }
                }
                mHeartData.setLockusertime(new Date());
                mHeartDao.addEvent(mHeartData);
                break;
            case ApiCmd.UPDATE_DB:

//                    GetDBCallBack getDBCallBack = new NetworkFragment();
                String name = JSON.parseObject(String.valueOf(json.toJSONString())).getString("name");
//                    getDBCallBack.onSuccess(name );

                Intent intent = new Intent();
                intent.setAction("CONNECTIVITY_CHANGE");
                intent.putExtra("name",name);
                mContext.sendBroadcast(intent);

                break;
            default:
                break;
        }
        return networkData;
    }

    private void sendBack(int cmd, String data) {
        BaseApi baseApi = new BaseApi(cmd,
                GlobalVariables.getInstance().getmSiteData().getSite(), new Object());
        if (!data.isEmpty()) baseApi.setData(data);
        WebSocketHelp.getmInstance().sendMessage((byte)cmd,JSON.toJSONString(baseApi));
    }
}
